/*********************************************************************/
//                        头文件
/*********************************************************************/
#include "flash.h"
#include "stm32f1xx_hal_flash.h"
#include "stm32f1xx_hal_flash_ex.h"

#define FLASH_SIZE 512          // 所选MCU的FLASH容量大小(单位为K)

#if FLASH_SIZE < 256
  #define SECTOR_SIZE 1024    // 字节
#else 
  #define SECTOR_SIZE 2048    // 字节
#endif



void Erase_FlashPage(uint32_t startAddress)
{
    uint32_t offsetAddress = startAddress - FLASH_BASE;
    uint32_t sectorPosition = offsetAddress / SECTOR_SIZE;
    uint32_t sectorStartAddress = sectorPosition * SECTOR_SIZE + FLASH_BASE;
    
    FLASH_EraseInitTypeDef EraseInitStruct;
    uint32_t SectorError = 0;
    
    HAL_FLASH_Unlock();
    
    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = sectorStartAddress;
    EraseInitStruct.NbPages = 1;
    
    HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError);
    
    HAL_FLASH_Lock();
}

// 从指定地址开始写入多个数据
void FLASH_WriteMoreData(uint32_t startAddress, uint16_t *writeData, uint16_t countToWrite)
{    
    uint32_t offsetAddress = startAddress - FLASH_BASE;
    uint32_t sectorPosition = offsetAddress / SECTOR_SIZE;
    uint32_t sectorStartAddress = sectorPosition * SECTOR_SIZE + FLASH_BASE;
    uint16_t dataIndex;
    
    if(startAddress < FLASH_BASE || ((startAddress + countToWrite * 2) >= (FLASH_BASE + SECTOR_SIZE * FLASH_SIZE)))
    {
        return; // 非法地址
    }
    
    HAL_FLASH_Unlock();
    
    // 擦除扇区
    FLASH_EraseInitTypeDef EraseInitStruct;
    uint32_t SectorError = 0;
    EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = sectorStartAddress;
    EraseInitStruct.NbPages = 1;
    HAL_FLASHEx_Erase(&EraseInitStruct, &SectorError);
    
    // 写入数据
    for(dataIndex = 0; dataIndex < countToWrite; dataIndex++)
    {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, startAddress + dataIndex * 2, writeData[dataIndex]);
    }
    
    HAL_FLASH_Lock();
}

// 读取指定地址的半字(16位数据)
uint16_t FLASH_ReadHalfWord(uint32_t address)
{
    return *(__IO uint16_t*)address; 
}

// 从指定地址开始读取多个数据
void FLASH_ReadMoreData(uint32_t startAddress, uint16_t *readData, uint16_t countToRead)
{
    uint16_t dataIndex;
    for(dataIndex = 0; dataIndex < countToRead; dataIndex++)
    {
        readData[dataIndex] = FLASH_ReadHalfWord(startAddress + dataIndex * 2);
    }
}

void write_to_flash(void)
{
    uint16_t buff[1] = {0xff};
//    uint16_t count_len = 2272 / 2;
    
    FLASH_WriteMoreData(StartServerManageFlashAddress, buff, 1); 
}
